package net.ibizsys.eclipse.studio.project;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.List;

import net.ibizsys.eclipse.studio.console.Console;
import net.ibizsys.eclipse.studio.data.Project;
import net.ibizsys.eclipse.studio.util.SystemKit;
import net.ibizsys.eclipse.studio.vc.SystemVCManager;
import net.ibizsys.eclipse.studio.vc.svn.SVNManager;

/**
 * 批处理文件构建基类
 * 
 * @author <a href='http://www.weibo.com/xjtoo' target='_blank'>Enmaai</a>
 */
public abstract class BaseBatchBuilder implements IBuilder
{
	/**
	 * Windows批处理文件名称
	 */
	public static final String WinBatchFileName = "winmerge.bat";

	/**
	 * Linux批处理文件名称
	 */
	public static final String LnxBatchFileName = "lnxmerge.sh";

	@Override
	public boolean init()
	{
		return true;
	}

	/**
	 * 构建Windows批处理文件
	 * 
	 * @param builder
	 * @param project
	 * @param dependProjects
	 * @param destPath
	 */
	protected abstract void buildWinBatch(StringBuilder builder, Project project, List<Project> dependProjects, String destPath);

	/**
	 * 构建Linux批处理文件
	 * 
	 * @param builder
	 * @param project
	 * @param dependProjects
	 * @param destPath
	 */
	protected abstract void buildLnxBatch(StringBuilder builder, Project project, List<Project> dependProjects, String destPath);

	@Override
	public boolean build(Project project, List<Project> dependProjects, String destPath)
	{
		FileOutputStream fos = null;
		BufferedWriter bw = null;
		File file = null;
		try
		{
			
			StringBuilder builder = new StringBuilder();
			if (SystemKit.isWindows())
			{
				file = new File(destPath + File.separator + project.getName() + File.separator + WinBatchFileName);
				buildWinBatch(builder, project, dependProjects, destPath);
			} else
			{
				file = new File(destPath + File.separator + project.getName() + File.separator + LnxBatchFileName);
				buildLnxBatch(builder, project, dependProjects, destPath);
			}
			
			if(file.exists())
			{
				Console.println("批处理文件已经存在，不再生成.");
				Console.println(builder.toString());
					
				return true;
			}	

			fos = new FileOutputStream(file);
			bw = new BufferedWriter(new OutputStreamWriter(fos));

			bw.write(builder.toString());
			bw.flush();
		} catch (Exception ex)
		{
			return false;
		} finally
		{
			try
			{
				fos.close();
			} catch (Exception ex)
			{
				ex.printStackTrace();
			}
			try
			{
				bw.close();
			} catch (Exception ex)
			{
				ex.printStackTrace();
			}
		}

		SystemVCManager.ignore(project.getSVNUrl(), file.getAbsolutePath());
		return true;
	}

}
